package com.caocaog.market.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.caocaog.market.entity.GoodsBasic;
import com.caocaog.market.entity.ShopBasic;
import com.caocaog.market.service.IGoodsBasicService;
import com.caocaog.market.service.IShopBasicService;
import com.caocaog.market.vo.GoodsAttributeVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.CommonAPI;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.domain.QueryRequest;
import org.jeecg.common.system.query.PageGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 商品表
 * @Author: guofeiyan
 * @Date: 2021-11-12
 * @Version: V1.0
 */
@Api(tags = "商品表")
@RestController
@RequestMapping("/goods/goodsBase")
@Slf4j
public class GoodsBasicController extends JeecgController<GoodsBasic, IGoodsBasicService> {
    @Autowired
    private IGoodsBasicService goodsBasicService;
    @Autowired
    private IShopBasicService shopBasicService;
    @Autowired
    private CommonAPI commonAPI;
    /*@Autowired
    private GoodsHisService goodsHisService;
    @Autowired
    private RedisUtil redisUtil;*/

    /**
     * 分页列表查询
     */
    @AutoLog(value = "商品表-分页列表查询")
    @ApiOperation(value = "商品表-分页列表查询", notes = "商品表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(GoodsBasic goodsBasic, QueryRequest queryRequest) {
        System.out.println(goodsBasic);
        queryRequest.setColumn("sort");
        Page<GoodsBasic> page = PageGenerator.createPageSort(queryRequest);
        page.addOrder(new OrderItem(CommonConstant.DEFAULT_ORDER_COLUMN, false));

        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (oConvertUtils.isNotEmpty(loginUser.getUserType()) && 1 != loginUser.getUserType()) {
            if (2 == loginUser.getUserType()) {

                //分站
                String siteId = loginUser.getSiteId();
                //获取商家ids
                List<String> merchantIds = commonAPI.findMerchantForSite(siteId);
                //获取门店
                if (oConvertUtils.listIsNotEmpty(merchantIds)){
                    List<String> shopIds = shopBasicService.list(new LambdaQueryWrapper<ShopBasic>()
                                    .in(ShopBasic::getMerchantId,merchantIds))
                            .stream().map(ShopBasic::getId).collect(Collectors.toList());
                   if (oConvertUtils.listIsNotEmpty(shopIds)) {
                       goodsBasic.setShopId(StringUtils.join(shopIds, StringPool.COMMA));
                   }
                }

            } else if (3 == loginUser.getUserType()){
                //商户
                String merchantId = loginUser.getMerchantId();
                //获取门店
                // 首先获取选择的门店
                if (oConvertUtils.isNotEmpty(loginUser.getCurrentSelectedShopId())){
                    goodsBasic.setShopId(loginUser.getCurrentSelectedShopId());
                }else {
                    List<String> shopIds = shopBasicService.list(new LambdaQueryWrapper<ShopBasic>()
                            .eq(ShopBasic::getMerchantId,merchantId))
                            .stream().map(ShopBasic::getId).collect(Collectors.toList());
                    if (oConvertUtils.listIsNotEmpty(shopIds)){
                        goodsBasic.setShopId(StringUtils.join(shopIds, StringPool.COMMA));
                    }else {
                        //当前无门店
                        return Result.error("您还没有自己的门店,请先添加自己的门店哟~");
                    }
                }
            }
        }
        return Result.OK(this.goodsBasicService.queryGoodsBasicPage(page, goodsBasic));
    }

    /**
     * 添加
     *
     * @param goodsBasic
     * @return
     */
    @AutoLog(value = "商品表-添加")
    @ApiOperation(value = "商品表-添加", notes = "商品表-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody GoodsBasic goodsBasic) {

        if ((oConvertUtils.isNotEmpty(goodsBasic.getOriginalPrice())
                &&Double.parseDouble(goodsBasic.getOriginalPrice())<Double.parseDouble("0.00"))
                || (oConvertUtils.isNotEmpty(goodsBasic.getPresentPrice())
                &&Double.parseDouble(goodsBasic.getPresentPrice())<Double.parseDouble("0.01"))) {
            return Result.error("价格不能小于0.01哟~");
        }
        List<GoodsAttributeVo> goodsSpecificationsVoList = goodsBasic.getGoodsSpecificationsVoList();
        if (goodsSpecificationsVoList.size()==0){
            return Result.error("请至少添加一个规格哟~");
        }
        for (GoodsAttributeVo goodsAttributeVo : goodsSpecificationsVoList) {
            if (oConvertUtils.isEmpty(goodsAttributeVo.getPriceSku())){
                return Result.error("规格价格不能为空哟");
            }
            if (StringUtils.isBlank(goodsAttributeVo.getPackFeeSku())){
                return Result.error("打包费不能为空");
            }
            if (Double.parseDouble(goodsAttributeVo.getPriceSku())<Double.parseDouble("0.01")) {
                return Result.error("价格不能小于0.01哟~");
            }
            if (goodsAttributeVo.getStockSku() < 0) {
                return Result.error("库存不能小于0");
            }
        }
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (StringUtils.isBlank(loginUser.getCurrentSelectedShopId()))
            throw new JeecgBootException("用户暂未绑定门店, realName-> " + loginUser.getRealname());
        goodsBasic.setShopId(loginUser.getCurrentSelectedShopId());
        Result add = goodsBasicService.add(goodsBasic);
        return add;
    }


    /**
     * 编辑
     *
     * @param goodsBasic
     * @return
     */
    @AutoLog(value = "商品表-编辑")
    @ApiOperation(value = "商品表-编辑", notes = "商品表-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody GoodsBasic goodsBasic) {
        if ((oConvertUtils.isNotEmpty(goodsBasic.getOriginalPrice())
                &&Double.parseDouble(goodsBasic.getOriginalPrice())<Double.parseDouble("0.00"))
                || (oConvertUtils.isNotEmpty(goodsBasic.getPresentPrice())
                &&Double.parseDouble(goodsBasic.getPresentPrice())<Double.parseDouble("0.01"))) {
            return Result.error("价格不能小于0.01哟~");
        }
        List<GoodsAttributeVo> goodsSpecificationsVoList = goodsBasic.getGoodsSpecificationsVoList();
        if (goodsSpecificationsVoList.size()==0){
            return Result.error("请至少添加一个规格哟~");
        }
        for (GoodsAttributeVo goodsAttributeVo : goodsSpecificationsVoList) {
            if (oConvertUtils.isEmpty(goodsAttributeVo.getPriceSku())){
                return Result.error("规格价格不能为空哟");
            }
            if (StringUtils.isBlank(goodsAttributeVo.getPackFeeSku())){
                return Result.error("打包费不能为空");
            }
            if (Double.parseDouble(goodsAttributeVo.getPriceSku())<Double.parseDouble("0.01")) {
                return Result.error("价格不能小于0.01哟~");
            }
            if (goodsAttributeVo.getStockSku() < 0) {
                return Result.error("库存不能小于0");
            }
        }
        Result update = goodsBasicService.update(goodsBasic);
        return update;
    }

    /**
     *   通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "商品分类表-通过id删除")
    @ApiOperation(value="商品分类表-通过id删除", notes="商品分类表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name="id",required=true) String id) {
        GoodsBasic goodsBasic = goodsBasicService.getById(id);
        this.goodsBasicService.removeById(id);
        goodsBasic.setDelFlag(1);
//        goodsHisService.insertGoodsHis(goodsBasic);
        return Result.OK("删除成功!",true);
    }

    /**
     *  批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "商品分类表-批量删除")
    @ApiOperation(value="商品分类表-批量删除", notes="商品分类表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
        String[] idList = ids.split(",");
//        this.goodsBasicService.removeByIds(Arrays.asList(idList));
        for (String id : idList){
            GoodsBasic goodsBasic = goodsBasicService.getById(id);
            goodsBasic.setDelFlag(1);
//            goodsHisService.insertGoodsHis(goodsBasic);
            this.goodsBasicService.removeById(id);
        }
        return Result.OK("批量删除成功!",true);
    }

    /**
     * 上下架状态开关更新
     *
     * @param id
     * @return
     */
    @AutoLog(value = "上下架状态开关更新-通过id更新")
    @ApiOperation(value = "上下架状态开关更新-通过id更新", notes = "上下架状态开关更新-通过id更新")
    @GetMapping(value = "/statusChange/{id}")
    public Result<?> statusChange(@PathVariable("id") String id) {
        GoodsBasic goodsBasic = goodsBasicService.getById(id);
        goodsBasic.setStatus(goodsBasic.getStatus().equals("0") ? "1" : "0");
        goodsBasicService.updateById(goodsBasic);
//        goodsHisService.insertGoodsHis(goodsBasic);
        return Result.OK("操作成功", goodsBasic);
    }

    /**
     * 首页状态开关更新
     *
     * @param id
     * @return
     */
    @AutoLog(value = "首页状态开关更新-通过id更新")
    @ApiOperation(value = "首页状态开关更新-通过id更新", notes = "首页状态开关更新-通过id更新")
    @GetMapping(value = "/isIndexChange/{id}")
    public Result<?> isIndexChange(@PathVariable("id") String id) {
        GoodsBasic goodsBasic = goodsBasicService.getById(id);
        goodsBasic.setIsIndex(goodsBasic.getIsIndex().equals("0") ? "1" : "0");
        goodsBasicService.updateById(goodsBasic);
//        goodsHisService.insertGoodsHis(goodsBasic);
        return Result.OK("操作成功", goodsBasic);
    }

    /**
     * 热门状态开关更新
     *
     * @param id
     * @return
     */
    @AutoLog(value = "热门状态开关更新-通过id更新")
    @ApiOperation(value = "热门状态开关更新-通过id更新", notes = "热门状态开关更新-通过id更新")
    @GetMapping(value = "/isHotChange/{id}")
    public Result<?> isHotChange(@PathVariable("id") String id) {
        GoodsBasic goodsBasic = goodsBasicService.getById(id);
        goodsBasic.setIsHot(goodsBasic.getIsHot().equals("0") ? "1" : "0");
        goodsBasicService.updateById(goodsBasic);
//        goodsHisService.insertGoodsHis(goodsBasic);
        return Result.OK("操作成功", goodsBasic);
    }

    /**
     * 删除状态开关更新
     *
     * @param id
     * @return
     */
    @AutoLog(value = "删除状态开关更新-通过id更新")
    @ApiOperation(value = "删除状态开关更新-通过id更新", notes = "删除状态开关更新-通过id更新")
    @GetMapping(value = "/delFlagChange/{id}")
    public Result<?> delFlagChange(@PathVariable("id") String id) {
        GoodsBasic goodsBasic = goodsBasicService.getById(id);
        goodsBasic.setDelFlag(goodsBasic.getDelFlag() == 0 ? 1 : 0);
        goodsBasicService.updateById(goodsBasic);
//        goodsHisService.insertGoodsHis(goodsBasic);
        return Result.OK("操作成功", goodsBasic);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "商品表-通过id查询")
    @ApiOperation(value = "商品表-通过id查询", notes = "商品表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        GoodsBasic goodsBasic = goodsBasicService.getById(id);
        if (goodsBasic == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(goodsBasic);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param goodsBasic
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, GoodsBasic goodsBasic) {
        return super.exportXls(request, goodsBasic, GoodsBasic.class, "商品表");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, GoodsBasic.class);
    }

}
